<template>
  <n-modal
    v-model:show="getProps.modalData.show"
    class="custom-card"
    preset="card"
    :style="{ width: '800px' }"
    :title="title"
    :bordered="false"
    :segmented="{
      content: true,
      footer: true
    }"
    :mask-closable="false"
  >
    <n-form ref="formRef" :model="form" label-placement="left" :label-width="160" :rules="rules">
      <n-form-item label="营业执照上传" path="licenseUrl">
        <x-upload
          v-model:value="form.licenseUrl"
          action="/api/account/store/qualification/parse/license"
          :limit="1"
          is-manual
          restriction-text="最多上传1张图片支持jpg、jpeg、png，图片大小不超2M"
          @success="handleLicenseParse"
        >
        </x-upload>
      </n-form-item>
      <n-form-item label="公司名称" path="licenseSerial">
        <n-input v-model:value="form.licenseSerial" placeholder="请输入公司营业执照上的名称" type="text" clearable />
      </n-form-item>
      <n-form-item label="联系人" path="licenseSerial">
        <n-input v-model:value="form.licenseSerial" placeholder="请输入联系人" type="text" clearable />
      </n-form-item>
      <n-form-item label="联系电话" path="companyName">
        <n-input v-model:value="form.companyName" type="text" clearable />
      </n-form-item>
      <n-form-item label="登录邮箱" path="companyName">
        <n-input v-model:value="form.companyName" type="text" clearable />
      </n-form-item>
      <n-form-item label="登录密码" path="companyName">
        <n-space align="center">
          <n-input-group>
            <n-input v-model:value="form.companyName" type="text" clearable />
            <x-button ghost>自动生成</x-button>
          </n-input-group>
          <n-text>未填写新密码，则保存原来的密码</n-text>
        </n-space>
      </n-form-item>
    </n-form>

    <template #footer>
      <n-space justify="end">
        <n-button @click="handleClose">取消</n-button>
        <n-button type="primary" :loading="loading" @click="handleSave">确定</n-button>
      </n-space>
    </template>
  </n-modal>
</template>

<script setup lang="ts">
  import { XUpload, XButton } from '@/components'
  import {
    NModal,
    NForm,
    NFormItem,
    NText,
    NInput,
    NInputGroup,
    NSpace,
    NButton,
    FormValidationError,
    useDialog
  } from 'naive-ui'
  import { useStore } from '@/store'
  import { computed, onMounted, reactive, ref } from 'vue'
  import { formatDate } from '@/utils'
  import { useDictionary } from '@/hooks'

  const store = useStore()
  const dialog = useDialog()
  const { get: getDict } = useDictionary()
  const emits = defineEmits(['success'])
  const props = defineProps({
    modalData: {
      type: Object,
      default: () => ({})
    }
  })

  const getProps = reactive(props)
  const loading = ref(false)
  const loadingDetail = ref(false)
  const formRef = ref(null)
  const form = ref({
    organizationType: 2, //主体类型：2-企业；4-个体工商户
    licenseUrl: '', //营业执照URL
    licenseMediaId: '', //营业执照ID
    licenseSerial: '', //纳税人识别号
    companyName: '', //公司名称
    companyAddress: '', //商户地址
    licenseStartDate: null, //营业执照有效期开始时间
    licenseEndDate: null, //营业执照有效期结束时间，没有结束时间代表长期有效
    merchantMobile: '', //法人手机号
    legalPerson: '', //法人姓名
    idCard: '' //法人身份证号
  })
  const initialData = ref({
    organizationType: 2, //主体类型：2-企业；4-个体工商户
    licenseUrl: '', //营业执照URL
    licenseMediaId: '', //营业执照ID
    licenseSerial: '', //纳税人识别号
    companyName: '', //公司名称
    licenseStartDate: null, //营业执照有效期开始时间
    licenseEndDate: null //营业执照有效期结束时间，没有结束时间代表长期有效
  })

  const rules = reactive({
    organizationType: { type: 'number', required: true, message: '请选择', trigger: 'change' },
    licenseUrl: { required: true, message: '请上传', trigger: 'change' },
    companyName: { required: true, message: '请输入', trigger: ['blur', 'input'] },
    companyAddress: { required: true, message: '请输入', trigger: ['blur', 'input'] },
    licenseSerial: [
      { required: true, message: '请输入', trigger: ['blur', 'input'] },
      { min: 15, max: 18, message: '长度为15-20个字符', trigger: ['blur', 'input'] }
    ],
    licenseStartDate: {
      type: 'number',
      required: true,
      message: '请选择',
      trigger: ['blur', 'change']
    }
  })
  const dictionary = computed(() => store.getters.dictionary)
  const title = props.modalData.type === 'add' ? '新增关联主体' : '编辑关联主体'
  const isEdit = computed(() => props.modalData.type === 'edit')

  onMounted(() => {
    getDict('ORGANIZATION_TYPE')
    if (props.modalData.row?.id) {
      getDetail()
    }
  })

  async function getDetail() {
    loadingDetail.value = true
    const { data } = await store
      .dispatch('store-manage/dominantDetail', {
        dominantId: props.modalData.row.id
      })
      .finally(() => {
        loadingDetail.value = false
      })

    if (data) {
      form.value = {
        ...data,
        licenseStartDate: +new Date(data.licenseStartDate),
        licenseEndDate: data.licenseEndDate ? +new Date(data.licenseEndDate) : null
      }

      initialData.value = {
        ...data,
        licenseStartDate: +new Date(data.licenseStartDate),
        licenseEndDate: data.licenseEndDate ? +new Date(data.licenseEndDate) : null
      }
    }
  }

  function handleClose() {
    getProps.modalData.show = false
  }

  function handleLongTermLicenseChange(checked: boolean) {
    if (checked) {
      form.value.licenseEndDate = null
    }
  }

  function handleLicenseParse(data: any) {
    form.value.licenseUrl = data.imageUrl
    recognizeLicenseInfo(data)
  }

  function recognizeLicenseInfo(data: any) {
    const { name, reg_num, establish_date, valid_period, address } = data
    const regNum = reg_num.replace(/\(|（/gi, '(').replace(/ /gi, '').split('(')[0]
    form.value.companyName = name === 'FailInRecognition' ? '' : name
    form.value.licenseSerial = reg_num === 'FailInRecognition' ? '' : regNum
    form.value.licenseStartDate =
      establish_date === 'FailInRecognition' || !establish_date ? null : getTimestamp(establish_date)
    form.value.companyAddress = address === 'FailInRecognition' ? '' : address
    if (valid_period === '29991231') {
      form.value.licenseEndDate = null
    } else {
      form.value.licenseEndDate = valid_period === 'FailInRecognition' ? null : getTimestamp(valid_period)
    }
  }

  function getTimestamp(date: string) {
    const dateArr = date.match(/(\d{4})(\d{2})(\d{2})/) as []
    dateArr.shift()
    return +new Date(dateArr)
  }

  function handleSave() {
    formRef.value?.validate(async (errors: Array<FormValidationError>) => {
      if (!errors) {
        if (isEdit.value) {
          const { organizationType, licenseUrl, licenseSerial, companyName, licenseStartDate, licenseEndDate } =
            form.value
          const {
            organizationType: iniOrganizationType,
            licenseUrl: iniLicenseUrl,
            licenseSerial: iniLicenseSerial,
            companyName: iniCompanyName,
            licenseStartDate: iniLicenseStartDate,
            licenseEndDate: iniLicenseEndDate
          } = initialData.value

          if (
            organizationType !== iniOrganizationType ||
            licenseUrl !== iniLicenseUrl ||
            licenseSerial !== iniLicenseSerial ||
            companyName !== iniCompanyName ||
            licenseStartDate !== iniLicenseStartDate ||
            licenseEndDate !== iniLicenseEndDate
          ) {
            dialog.create({
              title: '提示',
              content:
                '编辑主体后，原主体相关的合同以及授权书将会删除，且原主体关联的广告页面将会变更为新主体，可能会影响广告投放，请谨慎操作！',
              positiveText: '确定更改',
              negativeText: '取消',
              onPositiveClick: () => {
                submitData()
              }
            })

            return
          }
        }

        submitData()
      } else {
        console.log(errors)
      }
    })
  }

  async function submitData() {
    loading.value = true
    const { data } = await store
      .dispatch('store-manage/dominantSave', {
        ...form.value,
        licenseStartDate: formatDate(form.value.licenseStartDate),
        licenseEndDate: form.value.licenseEndDate ? formatDate(form.value.licenseEndDate) : null
      })
      .finally(() => {
        loading.value = false
      })
    emits('success', data)
    getProps.modalData.show = false
  }
</script>

<style scoped lang="scss"></style>
